﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NoORM.Core;
using NoORM.Core.Service;
using NoORM.Core.Contract;
using Microsoft.Extensions.Options;
using NoORM.Core.DbAcceess;

namespace Restsql.Api.Controllers
{
    /// <summary>
    /// 分页查询
    /// </summary>
    [Route("{database}/{table}.[controller]")]
    [ApiController]
    public class PageController : ControllerBase
    {
        /// <summary>
        /// 曾删改查的服务类对象
        /// </summary>
        private readonly CrudService service;

        /// <summary>
        /// 数据库连接字符串配置
        /// </summary>
        private readonly Dictionary<string, ConnectionStringConfig> configs;

        public PageController(IOptions<Dictionary<string, ConnectionStringConfig>> configsOption, CrudService service)
        {
            this.configs = configsOption.Value;
            this.service = service;
        }

        /// <summary>
        /// 新增一行数据
        /// </summary>
        /// <param name="database">数据库名</param>
        /// <param name="table">表名</param>
        /// <param name="pageRequest">分页参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Post(string database, string table, [FromBody] SqlRequest request)
        {
            PageResponse response = new PageResponse();
            response.ServerReceiveTime = DateTime.Now;
            var query = this.configs.Where(kv => kv.Key.Equals(database, StringComparison.CurrentCultureIgnoreCase));
            if (query == null || !query.Any())
            {
                response.Success = false;
                response.Message = "没有这个数据库";
                response.ServerSendTime = DateTime.Now;
                return new JsonResult(response);
            }
            ConnectionStringConfig config = query.First().Value;
            try
            {
                PageResponse result = await service.PageAsync(config, table, request);
                response.Success = result.Success;
                response.RowCount = result.RowCount;
                response.Message = result.Message;
                response.Data = result.Data;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                response.ServerSendTime = DateTime.Now;
            }
            response.ServerSendTime = DateTime.Now;
            TimeSpan timeSpan = response.ServerSendTime.Subtract(response.ServerReceiveTime);
            response.ServerUsedTime = timeSpan.Milliseconds + timeSpan.Seconds * 1000 + timeSpan.Minutes * 1000 * 60 + timeSpan.Hours * 1000 * 60 * 60;
            return new JsonResult(response);
        }
    }
}
